<template>
  <div class="shop-fee-standard-management">

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-card shadow="never">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="店铺">
            <el-select 
              v-model="searchForm.shopId" 
              placeholder="请选择店铺" 
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="费用类型">
            <el-select 
              v-model="searchForm.feeType" 
              placeholder="请选择费用类型" 
              clearable
              style="width: 150px"
            >
              <el-option label="物业费" value="PROPERTY" />
              <el-option label="水费" value="WATER" />
              <el-option label="电费" value="ELECTRIC" />
              <el-option label="燃气费" value="GAS" />
              <el-option label="卫生费" value="SANITATION" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="费用金额">
            <el-input-number
              v-model="searchForm.minFeeAmount"
              placeholder="最小金额"
              :precision="2"
              :min="0"
              style="width: 120px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input-number
              v-model="searchForm.maxFeeAmount"
              placeholder="最大金额"
              :precision="2"
              :min="0"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item label="生效日期">
            <el-date-picker
              v-model="searchForm.effectiveDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="过期日期">
            <el-date-picker
              v-model="searchForm.expiryDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.createTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="关键字">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索店铺名称、备注等"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-card shadow="never">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增费用标准
          </el-button>
          <el-button type="info" @click="handleExport" :disabled="standardList.length === 0">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="info" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-card shadow="never">
        <el-table 
          :data="standardList" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column prop="shopName" label="店铺名称" min-width="200" />
          <el-table-column prop="feeTypeName" label="费用类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getFeeTypeTagType(row.feeType)">
                {{ row.feeTypeName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="feeRate" label="费用标准" width="120">
            <template #default="{ row }">
              <span class="money-text">¥{{ formatMoney(row.feeRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="effectiveDate" label="开始日期" width="110" />
          <el-table-column prop="expiryDate" label="结束日期" width="110">
            <template #default="{ row }">
              {{ row.expiryDate || '长期' }}
            </template>
          </el-table-column>
          <el-table-column prop="statusName" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.statusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="150">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-card shadow="never">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 批量新增费用标准对话框 -->
    <BatchAddFeeStandardDialog
      v-model="showBatchDialog"
      @success="handleBatchSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  View, 
  Edit, 
  Delete 
} from '@element-plus/icons-vue'
import { shopFeeStandardApi, type FeeStandardQueryParams, type FeeStandardPageResult } from '@/api/region/shop-fee-standard'
import { shopApi } from '@/api/shop'
import type { ShopFeeStandardVO, ShopVO } from './types'
import BatchAddFeeStandardDialog from './components/BatchAddFeeStandardDialog.vue'

// 响应式数据
const loading = ref(false)
const standardList = ref<ShopFeeStandardVO[]>([])
const shopList = ref<ShopVO[]>([])
const showBatchDialog = ref(false)

// 搜索表单
const searchForm = reactive({
  shopId: undefined as number | undefined,
  feeType: undefined as string | undefined,
  status: undefined as number | undefined,
  minFeeAmount: undefined as number | undefined,
  maxFeeAmount: undefined as number | undefined,
  effectiveDateRange: undefined as string[] | undefined,
  expiryDateRange: undefined as string[] | undefined,
  createTimeRange: undefined as string[] | undefined,
  keyword: undefined as string | undefined
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 生命周期
onMounted(() => {
  loadStandardList()
  loadShopList()
})

// 方法
const loadStandardList = async () => {
  loading.value = true
  try {
    // 构建查询参数，遵循《Element Plus组件编码规范权威标准声明.md》规范
    const queryParams: FeeStandardQueryParams = {
      current: pagination.current,
      size: pagination.size,
      shopId: searchForm.shopId,
      feeType: searchForm.feeType,
      status: searchForm.status,
      minFeeAmount: searchForm.minFeeAmount,
      maxFeeAmount: searchForm.maxFeeAmount,
      effectiveDateStart: searchForm.effectiveDateRange?.[0],
      effectiveDateEnd: searchForm.effectiveDateRange?.[1],
      expiryDateStart: searchForm.expiryDateRange?.[0],
      expiryDateEnd: searchForm.expiryDateRange?.[1],
      createTimeStart: searchForm.createTimeRange?.[0],
      createTimeEnd: searchForm.createTimeRange?.[1],
      keyword: searchForm.keyword
    }
    
    // 调用真实API
    const response = await shopFeeStandardApi.getPage(queryParams)
    
    if (response && response.code === 200 && response.data) {
      standardList.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.current = response.data.current || 1
      pagination.size = response.data.size || 10
    } else {
      ElMessage.error(response?.message || '加载费用标准列表失败')
      standardList.value = []
    }
  } catch (error) {
    ElMessage.error('加载费用标准列表失败')
    console.error('加载费用标准列表失败:', error)
    standardList.value = []
  } finally {
    loading.value = false
  }
}

const loadShopList = async () => {
  try {
    // 调用真实API获取店铺列表，遵循《Element Plus组件编码规范权威标准声明.md》规范
    const response = await shopApi.getShopPage({
      current: 1,
      size: 1000, // 获取所有店铺
      status: 1 // 只获取启用的店铺
    })
    
    if (response && response.code === 200 && response.data) {
      // 过滤掉没有有效id的数据，遵循Element Plus组件编码规范
      shopList.value = (response.data.records || []).filter((item: any) => item.id != null)
    } else {
      ElMessage.error(response?.message || '加载店铺列表失败')
      shopList.value = []
    }
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
    shopList.value = []
  }
}

// 移除本地过滤函数，因为后端API已经处理了过滤逻辑

const handleSearch = () => {
  pagination.current = 1
  loadStandardList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    shopId: undefined,
    feeType: undefined,
    status: undefined,
    minFeeAmount: undefined,
    maxFeeAmount: undefined,
    effectiveDateRange: undefined,
    expiryDateRange: undefined,
    createTimeRange: undefined,
    keyword: undefined
  })
  handleSearch()
}

const handleAdd = () => {
  showBatchDialog.value = true
}

const handleEdit = (row: ShopFeeStandardVO) => {
  ElMessage.info('编辑费用标准功能开发中...')
}

const handleView = (row: ShopFeeStandardVO) => {
  ElMessage.info('查看费用标准功能开发中...')
}

const handleDelete = async (row: ShopFeeStandardVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除店铺"${row.shopName}"的费用标准吗？删除后不可恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    // 调用真实API删除，遵循《Element Plus组件编码规范权威标准声明.md》规范
    loading.value = true
    const response = await shopFeeStandardApi.delete(row.id)
    
    if (response && response.code === 200) {
      ElMessage.success('删除成功')
      loadStandardList()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  } finally {
    loading.value = false
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleRefresh = () => {
  loadStandardList()
}

const handleBatchSuccess = () => {
  showBatchDialog.value = false
  loadStandardList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadStandardList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadStandardList()
}

// 工具方法
const getFeeTypeTagType = (feeType: string) => {
  const typeMap = {
    'PROPERTY': 'primary',   // 物业费
    'WATER': 'info',         // 水费
    'ELECTRIC': 'warning',   // 电费
    'GAS': 'success',        // 燃气费
    'SANITATION': 'danger'   // 卫生费
  }
  return typeMap[feeType as keyof typeof typeMap] || 'info'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化金额，遵循《Element Plus组件编码规范权威标准声明.md》规范
const formatMoney = (value: number | string | null | undefined): string => {
  if (value === null || value === undefined || value === '') {
    return '0.00'
  }
  
  const numValue = typeof value === 'string' ? parseFloat(value) : value
  
  if (isNaN(numValue)) {
    return '0.00'
  }
  
  return numValue.toFixed(2)
}
</script>

<style scoped>
.shop-fee-standard-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.operation-area {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 16px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
